// 作品相关API服务
import pool from '../config/database';

class ArticleService {
  // 创建作品
  async createArticle(articleData) {
    const { user_id, title, description, content, content_html, cover_image, status = 'draft' } = articleData;

    const query = `
      INSERT INTO articles (user_id, title, description, content, content_html, cover_image, status)
      VALUES ($1, $2, $3, $4, $5, $6, $7)
      RETURNING *
    `;

    const values = [user_id, title, description || null, JSON.stringify(content), content_html, cover_image, status];

    try {
      const result = await pool.query(query, values);
      return result.rows[0];
    } catch (error) {
      console.error('创建作品失败:', error);
      throw error;
    }
  }

  // 更新作品
  async updateArticle(articleId, articleData) {
    const { title, description, content, content_html, cover_image, status } = articleData;

    const query = `
      UPDATE articles 
      SET title = $1, description = $2, content = $3, content_html = $4, cover_image = $5, status = $6, updated_at = CURRENT_TIMESTAMP
      WHERE id = $7
      RETURNING *
    `;

    const values = [title, description || null, JSON.stringify(content), content_html, cover_image, status, articleId];

    try {
      const result = await pool.query(query, values);
      return result.rows[0];
    } catch (error) {
      console.error('更新作品失败:', error);
      throw error;
    }
  }

  // 获取作品详情
  async getArticleById(articleId) {
    const query = `
      SELECT a.*, u.username, u.avatar_url
      FROM articles a
      LEFT JOIN users u ON a.user_id = u.id
      WHERE a.id = $1
    `;

    try {
      const result = await pool.query(query, [articleId]);
      if (result.rows.length === 0) {
        throw new Error('作品不存在');
      }

      const article = result.rows[0];
      // 解析JSON内容
      if (article.content) {
        article.content = JSON.parse(article.content);
      }

      // 获取附件信息，包括PDF转换结果
      // 先尝试从media_files表查询（新版本）
      let attachmentsQuery = `
        SELECT 
          mf.id,
          mf.original_name,
          mf.file_name,
          mf.file_url,
          mf.mime_type,
          mf.file_size,
          mf.file_type,
          mf.created_at,
          pdf.pdf_url,
          pdf.pdf_path,
          pdf.conversion_status as pdf_status
        FROM media_files mf
        LEFT JOIN pdf_conversions pdf ON mf.id = pdf.original_file_id
        WHERE mf.article_id = $1
        ORDER BY mf.created_at ASC
      `;

      let attachmentsResult = await pool.query(attachmentsQuery, [articleId]);

      // 如果media_files表中没有数据，尝试从attachments表查询（向后兼容）
      if (attachmentsResult.rows.length === 0) {
        attachmentsQuery = `
          SELECT 
            att.*,
            pdf.pdf_url,
            pdf.pdf_path,
            pdf.conversion_status as pdf_status
          FROM attachments att
          LEFT JOIN pdf_conversions pdf ON att.id = pdf.original_file_id
          WHERE att.article_id = $1
          ORDER BY att.created_at ASC
        `;

        try {
          attachmentsResult = await pool.query(attachmentsQuery, [articleId]);
        } catch (error) {
          console.warn('attachments表查询失败，可能不存在:', error.message);
          attachmentsResult = { rows: [] };
        }
      }

      // 处理附件数据，确保PDF信息正确
      article.attachments = attachmentsResult.rows.map(attachment => ({
        ...attachment,
        // 如果是PDF文件且没有pdf_url，使用原文件URL作为PDF URL
        pdf_url: attachment.pdf_url || (attachment.mime_type === 'application/pdf' ? attachment.file_url : null),
        pdf_status: attachment.pdf_status || (attachment.mime_type === 'application/pdf' ? 'completed' : 'unknown')
      }));

      return article;
    } catch (error) {
      console.error('获取作品失败:', error);
      throw error;
    }
  }

  // 获取作品列表
  async getArticles(options = {}) {
    const {
      page = 1,
      limit = 10,
      status = 'published',
      user_id,
      search
    } = options;

    const offset = (page - 1) * limit;

    let query = `
      SELECT a.id, a.title, a.content_html, a.cover_image, a.status, 
             a.view_count, a.like_count, a.comment_count, a.created_at, a.updated_at,
             u.username, u.avatar_url
      FROM articles a
      LEFT JOIN users u ON a.user_id = u.id
      WHERE 1=1
    `;

    const values = [];
    let paramIndex = 1;

    if (status) {
      query += ` AND a.status = $${paramIndex}`;
      values.push(status);
      paramIndex++;
    }

    if (user_id) {
      query += ` AND a.user_id = $${paramIndex}`;
      values.push(user_id);
      paramIndex++;
    }

    if (search) {
      query += ` AND (a.title ILIKE $${paramIndex} OR a.content_html ILIKE $${paramIndex})`;
      values.push(`%${search}%`);
      paramIndex++;
    }

    query += ` ORDER BY a.created_at DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
    values.push(limit, offset);

    try {
      const result = await pool.query(query, values);

      // 获取总数
      let countQuery = `
        SELECT COUNT(*) as total
        FROM articles a
        WHERE 1=1
      `;

      const countValues = [];
      let countParamIndex = 1;

      if (status) {
        countQuery += ` AND a.status = $${countParamIndex}`;
        countValues.push(status);
        countParamIndex++;
      }

      if (user_id) {
        countQuery += ` AND a.user_id = $${countParamIndex}`;
        countValues.push(user_id);
        countParamIndex++;
      }

      if (search) {
        countQuery += ` AND (a.title ILIKE $${countParamIndex} OR a.content_html ILIKE $${countParamIndex})`;
        countValues.push(`%${search}%`);
      }

      const countResult = await pool.query(countQuery, countValues);
      const total = parseInt(countResult.rows[0].total);

      return {
        articles: result.rows,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取作品列表失败:', error);
      throw error;
    }
  }

  // 删除作品
  async deleteArticle(articleId, userId) {
    const query = `
      DELETE FROM articles 
      WHERE id = $1 AND user_id = $2
      RETURNING *
    `;

    try {
      const result = await pool.query(query, [articleId, userId]);
      if (result.rows.length === 0) {
        throw new Error('作品不存在或无权限删除');
      }
      return result.rows[0];
    } catch (error) {
      console.error('删除作品失败:', error);
      throw error;
    }
  }

  // 增加浏览量
  async incrementViewCount(articleId) {
    const query = `
      UPDATE articles 
      SET view_count = view_count + 1
      WHERE id = $1
      RETURNING view_count
    `;

    try {
      const result = await pool.query(query, [articleId]);
      return result.rows[0]?.view_count || 0;
    } catch (error) {
      console.error('更新浏览量失败:', error);
      throw error;
    }
  }

  // 点赞/取消点赞
  async toggleLike(articleId, userId) {
    const client = await pool.connect();

    try {
      await client.query('BEGIN');

      // 检查是否已点赞
      const checkQuery = `
        SELECT id FROM likes 
        WHERE target_type = 'article' AND target_id = $1 AND user_id = $2
      `;
      const checkResult = await client.query(checkQuery, [articleId, userId]);

      let isLiked = false;

      if (checkResult.rows.length > 0) {
        // 取消点赞
        await client.query(
          'DELETE FROM likes WHERE target_type = $1 AND target_id = $2 AND user_id = $3',
          ['article', articleId, userId]
        );
        await client.query(
          'UPDATE articles SET like_count = like_count - 1 WHERE id = $1',
          [articleId]
        );
        isLiked = false;
      } else {
        // 添加点赞
        await client.query(
          'INSERT INTO likes (user_id, target_type, target_id) VALUES ($1, $2, $3)',
          [userId, 'article', articleId]
        );
        await client.query(
          'UPDATE articles SET like_count = like_count + 1 WHERE id = $1',
          [articleId]
        );
        isLiked = true;
      }

      // 获取最新点赞数
      const countResult = await client.query(
        'SELECT like_count FROM articles WHERE id = $1',
        [articleId]
      );

      await client.query('COMMIT');

      return {
        isLiked,
        likeCount: countResult.rows[0]?.like_count || 0
      };
    } catch (error) {
      await client.query('ROLLBACK');
      console.error('点赞操作失败:', error);
      throw error;
    } finally {
      client.release();
    }
  }
}

export default new ArticleService();